<?php
/**
 * Created by PhpStorm.
 * User: 64423
 * Date: 2018/10/16
 * Time: 11:41
 */

namespace app\shop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\shop\model\CouponModel;
use app\shop\model\UserModel;
use app\shop\model\UserLevelModel;

class Coupon extends Admin
{
    public function index()
    {
        $list = CouponModel::getAllList();
        $page = $list->render();
        $btn_access = [
            'title' => '发放',
            'icon'  => 'glyphicon glyphicon-send',
            'target' => '_self',
            'href'  => url('grant', ['uid' => '__id__'])
        ];
        return ZBuilder::make('table')
            ->setPageTitle('优惠券列表')
            ->setTableName('coupon')
            ->hideCheckbox()
            ->addColumns([
                ['name','优惠券名字'],
                ['type','优惠券类型'],
                ['thumb','图片','picture'],
                ['money','面额'],
                ['condition','使用条件'],
                ['createnum','发放数量'],
                ['send_num','已领取'],
//                ['use_num','已使用'],
                ['right_button','操作']
            ])
            ->addTopButton('add')
            ->addRightButtons('edit,delete')
            ->addRightButton('bbs',$btn_access,true)
            ->setRowList($list)
            ->setPages($page)
            ->fetch();
    }

    public function grant()
    {
        $data = input('.');
        $map = $this->getMap();
        unset($map['role']);
        $list = UserModel::getList($map);
        $count = db('user')->count('user_id');
        $page = $list->render();
        $list_role = UserLevelModel::getRes();
        $btn_access = [
            'title' => '发放',
            'icon'  => 'glyphicon glyphicon-send',
            'target' => '_self',
            'class' => 'btn btn-success',
            'href'  => url('grant')
        ];
        $html = "<div style='width:100%;height:34px;color:#000;font-size:15px;margin-bottom: 10px;font-weight: bolder;line-height: 34px;'>
                会员列表（共".$count."条记录）"."</div>";
        return ZBuilder::make('table')
            ->setPageTitle('发放优惠券')
            ->addTopSelect('role', '所有会员', $list_role)
            ->addTopButton('enable',$btn_access) // 添加顶部按钮

            ->setTableName('coupon')
            ->setSearch(['user_id' => 'ID', 'mobile' => '手机'])
            ->addColumns([
                ['user_id','会员ID'],
                ['level_name','会员等级'],
                ['nickname','会员昵称'],
                ['mobile','手机号码'],
            ])
            ->setRowList($list)
            ->setExtraHtml($html, 'toolbar_top')
            ->setPages($page)
            ->fetch();
    }

    public function add()
    {
        if(request()->isPost()){
            $this->store();
        }
        $js = $this->setJs();

        return ZBuilder::make('form')
            ->addFormItems([
                ['text','name','优惠券名称'],
                ['image','thumb','图片'],
                ['radio','type', '发放类型', '', ['0' => '下单赠送', '1' => '指定发放', '2' => '免费领取', '3' => '线下发放'],'0'],
                ['text','money','优惠券面额'],
                ['text','condition','使用门槛'],
                ['text','createnum','发放总数量'],
                ['datetime','send_start_time','发放起始时间',''],
                ['datetime','send_end_time','发放结束时间',''],
                ['datetime','use_start_time','使用起始时间',''],
                ['datetime','use_end_time','使用结束时间',''],
            ])
            ->setUrl(url('add'))
            ->setExtraJs($js)
            ->fetch();
    }

    public function edit($id=0)
    {
        if(request()->isPost()){
            $this->store();
        }
        $js = $this->setJs();
        $data = CouponModel::getOne($id);
        if($data['send_start_time']==0){
            $data['send_start_time'] = time();
            $data['send_end_time'] = time() + 2592000;  //一个月
        }
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden', 'id'],
                ['text','name','优惠券名称'],
                ['image','thumb','图片'],
                ['radio','type', '发放类型', '', ['0' => '下单赠送', '1' => '指定发放', '2' => '免费领取', '3' => '线下发放'],'0'],
                ['text','money','优惠券面额'],
                ['text','condition','使用门槛'],
                ['text','createnum','发放总数量'],
                ['datetime','send_start_time','发放起始时间',''],
                ['datetime','send_end_time','发放结束时间',''],
                ['datetime','use_start_time','使用起始时间',''],
                ['datetime','use_end_time','使用结束时间',''],
            ])
            ->setUrl(url('add'))
            ->setFormData($data)
            ->setExtraJs($js)
            ->fetch();
    }


    private function store()
    {
        $id = input('param.id',0);
        $data = input('post.');
        if($data['type']==0){
            $data['send_start_time'] = 0;
            $data['send_end_time'] = 1;  //一个月
        }
        $validate = new \app\shop\validate\Coupon();
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }
        $data['send_start_time'] = strtotime($data['send_start_time']);
        $data['send_end_time'] = strtotime($data['send_end_time']);
        $data['use_start_time'] = strtotime($data['use_start_time']);
        $data['use_end_time'] = strtotime($data['use_end_time']);

        $res = CouponModel::store($data, $id);
        if($res){
            $this->success('保存成功',url('index'));
        }else{
            $this->error('保存失败，请重试！');
        }
    }

    private function setJs()
    {
        $js = <<<EOF
    <script>
        $(function() {
          var vals = $('input:radio:checked').val();
          if(vals == 0){
                hideAll();
            }else{
                $("#form_group_send_start_time").show();
                $("#form_group_send_end_time").show();
            }
            
          $("#form_group_type").on('change', function() {
           var val = $('input:radio:checked').val();

            if(val == 0){
                hideAll();
            }else{
                $("#form_group_send_start_time").show();
                $("#form_group_send_end_time").show();
            }
          })
        });
        function hideAll() {
          $("#form_group_send_start_time").hide();
          $("#form_group_send_end_time").hide();
        }
    </script>
EOF;
        return $js;
    }

    public function delete($ids = 0)
    {
        $res =  CouponModel::del($ids);
        if($res){
            $this->success('删除成功',url('index'));
        }else{
            $this->error('删除失败');
        }
    }
}